import React, { useEffect, useState } from 'react';
import {
  Collapse, Spin, message, Typography, Space, List
} from 'antd';
import { fetchUserAnswers, fetchSurveyByIdAny } from '../services/survey';
import { getEmailFromToken } from '../utils/getemailfromtoken';

const { Text } = Typography;
const { Panel } = Collapse;

const ViewAnsweredSurveys = () => {
  const [data, setData] = useState([]);
  const [loading, setLoading] = useState(true);
  const email = getEmailFromToken();

  useEffect(() => {
    const loadData = async () => {
      try {
        const answers = await fetchUserAnswers(email);
        const result = await Promise.all(
          answers.map(async (answer) => {
            const survey = await fetchSurveyByIdAny(answer.surveyId);
            return { survey, answer };
          })
        );
        setData(result);
      } catch (err) {
        message.error(err.message);
      } finally {
        setLoading(false);
      }
    };

    loadData();
  }, [email]);

  if (loading) return <Spin tip="加载中..." />;

  return (
    <Collapse accordion expandIconPosition="end" style={{ width: '90%', margin: '20px auto' }}>
      {data.map(({ survey, answer }, index) => {
        const submitTime = new Date(answer.submitTime).toLocaleString();
        const status = survey.status || '未知状态';

        return (
          <Panel
            key={index}
            header={
              <div style={{
                display: 'flex',
                alignItems: 'center',
                gap: '40px', // 相当于五个空格
                paddingRight: 16
              }}>
                <Text >{survey.title}</Text>
                <Text type="secondary">{submitTime}</Text>
                <Text style={{ color: status === 'published' ? 'blue' : 'red' }}>
                  {status}
                 </Text>

              </div>
            }
          >
            <Space direction="vertical" style={{ width: '100%' }}>
              <Text type="secondary">问卷描述：{survey.description || '（无）'}</Text>

              <div>
                <Text strong>答题内容：</Text>
                <List
                  dataSource={survey.questions}
                  renderItem={(question, qIndex) => (
                    <List.Item key={qIndex}>
                      <div>
                        <Text >
                          {qIndex + 1}. {question.title}
                        </Text>
                        <div>
                          答案：{Array.isArray(answer.answers[qIndex])
                            ? answer.answers[qIndex].join(', ')
                            : answer.answers[qIndex]}
                        </div>
                      </div>
                    </List.Item>
                  )}
                />
              </div>
            </Space>
          </Panel>
        );
      })}
    </Collapse>
  );
};

export default ViewAnsweredSurveys;
